﻿var changeFlag = false;

function MarkDataChangedInPage() {
    changeFlag = true;
};

function MarkNoDataChangedInPage() {
    changeFlag = false;
}

function HasDataChangedInPage() {
    return changeFlag;
}

function RegisterControlDataChange(selector) {
    var inputs = $(selector + ' input');
    if (inputs.length > 0) {
        inputs.keyup(function () {
            MarkDataChangedInPage();
        });
    }

    var selects = $(selector + ' select');
    if (selects.length > 0) {
        selects.change(function () {
            MarkDataChangedInPage();
        });
    }
}

//the function will be overwrite for each tabs.
function RegisterBeforeUnloadPage(window, fnSave) {
    $(window).bind("beforeunload", function () {
        if (HasDataChangedInPage()) {
            var result = confirm('Some data has just been changed but not saved. Do you want to save the changes?');
            if (result == true) {
                if (typeof fnSave == "function") {
                    fnSave();
                }
            }
            else {
                MarkNoDataChangedInPage();
            }

        }
    });
}
